import sys

from PyQt5.QtCore import Qt, QRect
from PyQt5.QtGui import QPainter, QColor, QRegion, QPen
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QHBoxLayout, QMessageBox)

from image_to_text import image_to_text_paddle


class ScreenShotWidget(QWidget):
    # class ScreenShotWidget(QMainWindow):
    def __init__(self, bg_img=None):
        super().__init__()
        self.dragging = False
        self.is_drawing = False  # 新增：明确选区绘制状态
        self.start_pos = None
        self.end_pos = None
        self.bg_img = bg_img

        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        # self.setMouseTracking(True)
        # self.setWindowOpacity(0.5)
        self.showFullScreen()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.is_drawing = True  # 开始绘制选区
            self.start_pos = event.pos()
            self.end_pos = None

    def mouseReleaseEvent(self, event):
        if self.dragging:
            self.dragging = False
            self.is_drawing = False  # 结束绘制选区
            self.end_pos = event.pos()
            # self.label.setText(f"start_pos: {self.start_pos}, end_pos: {self.end_pos}")
            # self.update()

            select_rect = QRect(self.start_pos, self.end_pos).normalized()

            # 图片名称
            image_name = "screenshot.png"

            screen = QApplication.primaryScreen()
            screen.grabWindow(0, select_rect.x(), select_rect.y(), select_rect.width(),
                              select_rect.height()).save(image_name)
            txt = image_to_text_paddle(image_name)

            # 赋值到剪切板上
            clipboard = QApplication.clipboard()
            clipboard.setText(txt)
            print(txt)
            QMessageBox.information(self, "提示", f'"{txt}"已复制到剪切板')
            self.close()

    def mouseMoveEvent(self, event):
        # 获取鼠标的当前位置
        mouse_x = event.globalX()
        mouse_y = event.globalY()
        x = event.x()
        y = event.y()
        self.end_pos = event.pos()
        self.update()
        # 更新标签的文本
        # self.statusBar().showMessage(
        #     f"全局点击: X={mouse_x} Y={mouse_y} 按键={'左键' if event.button() == Qt.LeftButton else '右键'}")
        # self.label.setText(f"mouse_x: {mouse_x}, mouse_y: {mouse_y}，x: {x}, y: {y},pos: {event.pos()}")

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self)
        if self.bg_img:
            painter.drawPixmap(self.rect(), self.bg_img)  # 覆盖整个窗口绘制背景图
        # 步骤1：绘制半透明背景（覆盖整个窗口）
        bg_color = QColor(70, 70, 70, 200)  # 与setStyleSheet的半透明效果一致
        full_rect = self.rect()

        if self.start_pos and self.end_pos:
            # 步骤2：绘制半透明矩形
            select_rect = QRect(self.start_pos, self.end_pos).normalized()
            painter.setClipRegion(QRegion(full_rect) - QRegion(select_rect))
            painter.fillRect(full_rect, bg_color)
            # 步骤3：绘制矩形边框
            # 清除裁剪区域
            # painter.setClipRegion(QRegion())
            border_pen = QPen(QColor(255, 0, 0), 2, Qt.DashLine)  # 红色虚线边框
            painter.setPen(border_pen)
            painter.drawRect(select_rect)
        else:
            painter.fillRect(full_rect, bg_color)

            # 步骤3：绘制矩形边框（可选）

        # if self.is_drawing or (self.start_pos and self.end_pos):  # 拖动中或已完成选区:
        #     # 基于起始点和结束点绘制矩形（自动处理坐标顺序）
        #     rect = QRect(self.start_pos, self.end_pos).normalized()
        #     transparent_color = QColor(255, 255, 255, 0)  # 完全透明
        #     print(".................")
        #     painter.fillRect(rect, transparent_color)
        #
        #     # 步骤4：添加选区边框（参考gui_test.py的可见性优化）
        #     border_pen = QPen(QColor(255, 0, 0), 2, Qt.DashLine)  # 红色虚线边框
        #     painter.setPen(border_pen)
        #     painter.drawRect(rect)  # 绘制边框增强可见性


class MainWindow(QMainWindow):
    # class MainWindow(QWidget):
    screenshot_button: QPushButton

    def handle_global_click(self, x, y, button):
        self.statusBar().showMessage(
            f"全局点击: X={x} Y={y} 按键={'左键' if button == Qt.LeftButton else '右键'}")

    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("My Tools")
        self.setGeometry(100, 100, 400, 300)

        center_widget = QWidget()
        self.setCentralWidget(center_widget)

        self.layout = QHBoxLayout()
        # self.layout.setAlignment(Qt.AlignCenter)

        self.screenshot_button = QPushButton("截屏工具")
        self.screenshot_button.clicked.connect(self.screenshot)
        self.exit_button = QPushButton("退出")
        self.exit_button.clicked.connect(self.close)

        self.layout.addWidget(self.screenshot_button)
        self.layout.addWidget(self.exit_button)
        center_widget.setLayout(self.layout)

    def mousePressEvent(self, event):
        pass
        # screen_shot_widget = ScreeShotWidget()
        # screen_shot_widget.show()

        # print(f"鼠标在位置 {event.pos().x()},{event.pos().y()} 按下")
        # QMessageBox.information(self, "提示", "鼠标按下事件触发")

        # # 判断按键类型
        # if event.button() == Qt.LeftButton:
        #     print("左键按下")
        # elif event.button() == Qt.RightButton:
        #     print("右键按下")
        # def on_click(x, y, button, pressed):
        #     if pressed:
        #         print(f"{button}在({x},{y})按下")

        # listener = mouse.Listener(on_click=on_click)
        # listener.start()
        # super().mousePressEvent(event)

    def get_other_window_ids(self):
        # 获取当前应用的所有顶层窗口
        top_windows = QApplication.topLevelWidgets()
        window_ids = []
        for window in top_windows:
            # 排除自身（当前 MainWindow）
            if window != self:
                window_id = window.winId()  # 获取窗口 ID
                window_ids.append(window_id)
        return window_ids

    def screenshot(self):
        screen = QApplication.primaryScreen()
        dip = screen.grabWindow(0)

        self.screen_shot_widget = ScreenShotWidget(dip)
        self.screen_shot_widget.show()
        # screen_shot_widget.keyPressEvent(Qt.Key_Control)

    def close(self) -> bool:
        print("close")
        return super().close()


if __name__ == "__main__":
    application = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(application.exec_())
